﻿using Microsoft.Extensions.FileProviders;
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Reader.Core
{
    public class EmbeddedResourceZipFileInfo : IFileInfo
    {
        private readonly Assembly _assembly;
        private readonly string _zipPath;
        private readonly string _fullname;

        public EmbeddedResourceZipFileInfo(Assembly assembly, string zipPath, string fullname, string name, long length, DateTimeOffset lastModified)
        {
            _assembly = assembly;
            _zipPath = zipPath;
            _fullname = fullname;
            Name = name;
            Length = length;
            LastModified = lastModified;
        }

        public bool Exists => true;

        public bool IsDirectory => false;

        public DateTimeOffset LastModified { get; }

        public long Length { get; }

        public string Name { get; }

        public string PhysicalPath => null;

        public Stream CreateReadStream()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            var resources = _assembly.GetManifestResourceNames();
            var nameSpace = _assembly.EntryPoint.DeclaringType?.Namespace;
            var path = resources.SingleOrDefault(it => it == $"{nameSpace}.{_zipPath}");
            if (string.IsNullOrEmpty(path))
            {
                throw new FileNotFoundException($"not found {_zipPath}");
            }
            using (var stream = _assembly.GetManifestResourceStream(path))
            {
                using (var archinve = new ZipArchive(_assembly.GetManifestResourceStream(path), ZipArchiveMode.Read, true, Encoding.GetEncoding("GBK")))
                { 
                    var entry = archinve.Entries.SingleOrDefault(e => e.FullName == _fullname);
                    return entry.Open();
                }
            }
        }
    }
}
